package MathCore.Renders;

import MathCore.Expression;
import MathCore.Lexeme;
import MathCore.Operators.ArOperator;
import MathCore.Render;
import MathCore.Symbol;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author Александр
 */
public class Power extends Block
{
	private int yshift = Render.getFont().getHeight()/2;
	public Stripe line1;

	public Power()
	{
	}

	public Power(Stripe line1)
	{
		set(line1);
	}

	public void set(Stripe line1)
	{
		this.line1 = line1;
		line1.parent = this;
		line1.next = line1.prev = null;
	}

	public int width()
	{
		return line1.width();
	}

	public int height()
	{
		if(prev == null) return Render.getFont().getHeight() - yshift + line1.height();
		else return prev.height() - yshift + line1.height();
	}

	public int center()
	{
		if(prev == null) return Render.getFont().getHeight()/2;
		else return prev.center();
	}

	public Block first()
	{
		return line1;
	}

	public Block last()
	{
		return line1;
	}

	public void draw(Graphics g, int x, int y, int style)
	{
		saveCoordinates(x, y, style);

		// смещаем координаты, учитывая стили
		if(style(style, Block.TOP))		y += (height() - center());
		if(style(style, Block.BOTTOM))	y -= center();
		if(style(style, Block.RIGHT))	x -= width();
		if(style(style, Block.HCENTER))	x -= width()/2;

		//line1.draw(g, x, y, Block.VCENTER|Block.LEFT);

		x += Render.spacing;
		//y += line1.center();
		if(prev == null) y -= Render.getFont().getHeight();
		else
		{
			y += prev.center();
			y -= prev.height();
		}
		y += yshift;
		
		line1.draw(g, x, y, Block.LEFT|Block.BOTTOM);

		if(g == null) return;

		if(Render.activeBlock == this && Render.useCursor)
		{
			y -= line1.height();
			x += line1.width();
			g.setColor(Render.linkColor);
			g.drawLine(x, y, x, y+height());
			g.drawLine(x, y+height(), x-width(), y+height());
		}
	}

	public Block findLinked(Lexeme lex)
	{
		Block linked;
		if(lex == link) return this;
		linked = line1.findLinked(lex);
		return linked;
	}

	public String toString()
	{
		return "<power>";
	}

	public void extract(Expression exp)
	{
		exp.add(new ArOperator(ArOperator.POWER));
		exp.add(new Symbol(Symbol.LEFT_BRACE));
		line1.extract(exp);
		exp.add(new Symbol(Symbol.RIGHT_BRACE));
	}

	public void parse()
	{
		if(line1 != null) line1.parse();
	}
}
